<?php

namespace App\Http\Controllers;

use App\Exceptions\InvalidRequestException;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{
    public function payByAlipay(Order $order, Request $request)
    {
        $this->authorize('own', $order);
        if ($order->paid_at || $order->closed) {
            throw new InvalidRequestException('订单状态不正确');
        }

        return app('alipay')->web([
            'out_trade_no' => $order->no, // 订单编号，需保证在商户端不重复
            'total_amount' => $order->total_amount, // 订单金额，单位元，支持小数点后两位
            'subject'      => '支付 Laravel Shop 的订单：'.$order->no, // 订单标题
        ]);
    }

    /**
     * 支付宝前端回调
     * 支付成功后，浏览器跳转到项目页面
     * @return void
     */
    public function alipayReturn()
    {
        try {
            app('alipay')->callback();
        } catch (\Exception $e) {
            return view('pages.error', ['msg' => '数据不正确']);
        }

        return view('pages.success', ['msg' => '付款成功']);

    }


    /**
     * 支付宝服务端回调：是指支付成功之后支付宝的服务器会用订单相关数据作为参数请求项目的接口，不依赖用户浏览器
     * 因此我们判断支付是否成功要以服务器端回调为准。
     * @return void
     */
    public function alipayNotify()
    {
        /*
         * data 结果
        {
        "gmt_create": "2023-12-05 17:31:00",
        "charset": "utf-8",
        "gmt_payment": "2023-12-05 17:31:09",
        "notify_time": "2023-12-05 17:31:11",
        "subject": "支付 Laravel Shop 的订单：20231130141955743887",
        "buyer_id": "2088722023415602",
        "invoice_amount": "7251.00",
        "version": "1.0",
        "notify_id": "2023120501222173110015600501531548",
        "fund_bill_list": "[{\"amount\":\"7251.00\",\"fundChannel\":\"ALIPAYACCOUNT\"}]",
        "notify_type": "trade_status_sync",
        "out_trade_no": "20231130141955743887",
        "total_amount": "7251.00",
        "trade_status": "TRADE_SUCCESS",
        "trade_no": "2023120522001415600501498630",
        "auth_app_id": "9021000132649038",
        "receipt_amount": "7251.00",
        "point_amount": "0.00",
        "buyer_pay_amount": "7251.00",
        "app_id": "9021000132649038",
        "seller_id": "2088721023390443"
        }*/
        $data = app('alipay')->callback();
        Log::debug('alipay_notify',$data->all());
        if ( ! in_array($data->trade_status, ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
            return app('alipay')->success();
        }
        $order = Order::where('no', $data->out_trade_no)->first();
        if ( ! $order) {
            return 'fail';
        }
        if ($order->pait_at) {
            return app('alipay')->success();
        }

        $order->update([
            'paid_at'        => Carbon::now(),
            'payment_method' => 'alipay',
            'payment_no'     => $data->trade_no,
        ]);

        return app('alipay')->success();
    }
}
